package cn.ai.shoes.core.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import jodd.util.StringUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
@Component
public class AliyunOssUtils {
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    // source = "C:\\Users\\Administrator\\Pictures\\comfyuitest\\model\\board_shoes.jpg";
    // target = "board_shoes1.jpg";
    public String createFile (String source,String target) throws Exception {
        if (StringUtil.isEmpty(source)) {
            throw new Exception("文件路径为空");
        }
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, target, new ByteArrayInputStream(Files.readAllBytes(new File(source).toPath())));
        } catch (Exception e) {
            throw new Exception("上传失败: " + e.getMessage());
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return target;
    }
    public String createFile (InputStream inputStream, String target) throws Exception {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, target, inputStream);
        } catch (Exception e) {
            throw new Exception("上传失败: " + e.getMessage());
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return target;
    }

    public InputStream getFileInputStream(String target) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取OSS对象
            OSSObject ossObject = ossClient.getObject(bucketName, target);
            // 获取文件输入流
            return ossObject.getObjectContent();
        } catch (Exception e) {
            e.printStackTrace();
            // 发生异常时关闭客户端并返回null
            ossClient.shutdown();
            return null;
        }
    }

    public String getUrl(String ossPath) {
        // 参数验证
        if (StringUtil.isEmpty(ossPath)) {
            throw new IllegalArgumentException("ossPath 不能为空");
        }
        
        // 确保 endpoint 格式正确（去掉 https:// 前缀）
        String cleanEndpoint = endpoint;
        if (endpoint.startsWith("https://")) {
            cleanEndpoint = endpoint.substring(8);
        } else if (endpoint.startsWith("http://")) {
            cleanEndpoint = endpoint.substring(7);
        }
        
        // 构建正确的 OSS URL 格式
        // 阿里云 OSS 的标准 URL 格式：https://bucket-name.endpoint/object-key
        return "https://" + bucketName + "." + cleanEndpoint + "/" + ossPath;
    }
}
